package com.thoughtworks.rhinoextension.javamodel;

import org.mozilla.javascript.NativeArray;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.UniqueTag;

import java.util.ArrayList;
import java.util.List;

public class TestResultBuilder {

    public TestResult build(ScriptableObject testResults) {
        ScriptableObject stats = (ScriptableObject) testResults.get("stats", testResults);
        int passes = jsToJava(testResults, stats, "passes", Number.class).intValue();
        int failures = jsToJava(testResults, stats, "failures", Number.class).intValue();
        int duration = jsToJava(testResults, stats, "duration", Number.class).intValue();
        return new TestResult(passes, failures, duration, buildTestSuites(testResults));
    }

    private <T> T jsToJava(ScriptableObject testResults, ScriptableObject stats, String name, Class<T> type) {
        return (T) stats.get(name, testResults);
    }

    private List<TestSuite> buildTestSuites(ScriptableObject testResults) {
        ArrayList<TestSuite> suiteArrayList = new ArrayList<TestSuite>();

        Object allSuites = testResults.get("allSuites", testResults);
        if (!(allSuites instanceof NativeArray)) return suiteArrayList;

        NativeArray suites = (NativeArray) allSuites;
        int suitesCount = (int) suites.getLength();
        for (int i = 0; i < suitesCount; i++) {
            suiteArrayList.add(new TestSuite());
        }
        return suiteArrayList;
    }
}
